package controllers;

import models.User;
import play.Logger;
import play.Play;
import play.libs.F.Promise;
import play.libs.WS;
import play.libs.WS.Response;
import play.mvc.Controller;
import play.mvc.Result;
import services.UserService;
import util.UserSession;
import exceptions.NoUUIDException;

public class Filyou extends Controller{
	public static final UserService userService = UserService.getInstance();

	public static Result linkCallback(Long cid, Boolean success){
		try {
			UserSession userSession = userService.getUserSession(session());
			// If filyou redirect returned a success message
			if(success){
				User user = User.finder.where().eq("filyouId", cid).findUnique();
				user.filyouLinked = true;

				user.save();
				userSession.setUser(user);// update user in memory
				// update user from cache
				userService.updateExistingUserSession(userSession);

				return redirect(routes.Connect.index());
			}

			return badRequest();
		} catch (NoUUIDException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return redirect(routes.Connect.index());
	}

	//TODO make it work remotely
	public static Result unlink(Long cid){
		try {
			UserSession userSession = userService.getUserSession(session());

			//TODO add remote option later
//			String filyou = Play.application().configuration().getString("sm.filyou.unlink");
//			filyou = filyou.replaceAll("USER_ID", id + "");
//			// Try to unlink account on filyou server
//			Promise<WS.Response> result = WS.url(filyou).get();

			// If the HTTP STATUS is 200 than account is unlinked
			if (/*result.get().getStatus() == 200 && */ userSession.getUser().filyouId.equals(cid)) {
				// Get a user from database. Necessary for persistence. For this to word this method should be annotated with @play.db.jpa.Transactional
				collectors.file.controllers.FileYOUController.cleanLinkInfo(cid);
				User user = User.finder.where().eq("filyouId", cid).findUnique();
				user.filyouLinked = false; // update link status
				user.save();
				userSession.setUser(user);// update user in memory
				// update user from cache
				userService.updateExistingUserSession(userSession);
				
				return redirect(routes.Connect.index());
			} else {
				badRequest("Error trying to unlink FilYOU");
			}
		} catch (NoUUIDException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return redirect(routes.Connect.index());
	}
	
}
